<template>
  <div class="goods-detail">
    <!-- 商品图片轮播 -->
    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="(img,i) in carouselList" :key="i">
        <van-image width="80%" :src="$fullUrl(img)"/>
      </van-swipe-item>
    </van-swipe>
    <!-- 商品 明细 -->
    <van-cell title="商品编号" :value="goods.id"/>
    <van-cell title="商品名称" :label="goods.name"/>

    <van-cell title="商品规格" :label="goods.spec"/>
    <van-cell title="单价" :value="goods.price"/>
    <van-cell title="库存数量" :value="goods.count"/>
    <van-cell title="上架时间" :value="createTime"/>

    <!-- 商品购买区域 -->
    <van-cell title="购买数量">
      <template #label>
        <div class="count-buy">
          <van-stepper v-model="count" integer/>
          <van-button type="primary" size="small" @click="handleAddCart">加入购物车</van-button>
        </div>
      </template>
    </van-cell>

    <van-button type="primary" size="large" @click="handleBack">返回</van-button>
  </div>
</template>

<script>
//1.导入封装后的接口
import * as GoodsAPI from "@/api/goods.js";
import * as CartAPI from "@/api/cart.js";
// 导入日期处理第三方工具模块
import dayjs from "dayjs"

export default {
  // 数据
  data() {
    return {
      goods: {}, //商品对象（详情）
      carouselList: [], //商品轮播图片数组
      count: 0, //步进器绑定的数量
    }
  },
  // 方法
  methods: {
    handleBack() {
      this.$router.go(-1)
    },
    //处理添加购物车
    handleAddCart() {
      let params = {
        goodsId: this.goods.id,
        count: this.count,
      };
      //2.使用封装后的接口,注意接口参数
      CartAPI.addCart(params).then(result => {
        this.$toast(result.message);
      }).catch((err) => {
        console.log(err)
      });
    },
  },
  // 计算属性
  computed: {
    createTime() {
      return dayjs(this.goods.createTime).format("YYYY年MM月DD日");
    }
  },
  // 生命周期钩子-实例创建后,可以用this.*
  created() {
    let id = this.$route.params.id;
    //2.使用封装后的接口
    GoodsAPI.getDetailById(id).then(result => {
      // console.log(result);
      this.goods = result.data //保存API调用的返回数据
      //根据返回数据生成轮播图数组（用商品的中图片）
      this.carouselList = this.goods.album
    });
  },
}
</script>
<!-- 样式 -->
<style>
.goods-detail {
  background-color: white;
}

.van-swipe-item {
  text-align: center;
}

.count-buy {
  display: flex;
  flex-direction: row;
  margin: 10px 0px;
  justify-content: flex-end;
  align-items: center;
}

.van-stepper {
  padding: 0px 10px;
}
</style>
